#!/usr/bin/env python
# coding: UTF-8
#filename: D:/workspace/python/demo/mybatishandler/SQLGenerater.py
from mybatishandler import CommonConstants


'''
Created on 2013-7-12 下午3:44:19

@author: zhanghu
'''

class SQLGenerater(object):
    '''
    classdocs
    '''
    tableName = None
    propertyValue = '#{%s, jdbcType=%s}'


    def __init__(self, mapper):
        '''
        Constructor
        '''
        self.mapper = mapper
        self.mainFields = []
        
    def generate(self):
        pass
    
    def getMainFields(self):
        if '*' in self.mainFields:
            return [field.get('column') for field in self.mapper.getAllField()]
        else:
            return self.mainFields
    
    def setMainFeilds(self, mainFields):
        self.mainFields = mainFields
    
    def list2Str(self, toList):
        if toList is None or len(toList) == 0:
            return;
        
        # buffer for +
        return ', '.join(toList)
    
    # build field proterty
    def generateProValue(self):
        if SQLGenerater.isMapperOK(self):
            if CommonConstants.DEBUG:
                print 'error: 指定的mapper为空, 生成property value 失败！'
            return;
        result = []
        
        allFields = self.mapper.getAllField()
        
        for field in self.getMainFields():
            for mapField in allFields:
                column = str(mapField.get('column', None))
                if column is not None and column == field or (CommonConstants.IGNORE_CASE and column.upper() == field.upper()):
                    result.append(self.propertyValue % (mapField.get('property'), mapField.get('jdbcType')))
        
        return result
    
    def setMapper(self, mapper):
        self.mapper = mapper
    
    def isMapperOK(self):
        return self.mapper == None

class SelectSQLGenerater(SQLGenerater):
    #TODO 增强sql
    selectSql_template = 'select %s form %s '
   


    def __init__(self, dialect, mapper):
        SQLGenerater.__init__(self, mapper)
        self.dialect = dialect
        
    def generate(self):
        fields = self.wrapperFieldDefaultValue()
        fields = self.list2Str(fields)
        return self.selectSql_template % (fields, self.tableName)
    
    def generateProValue(self):
        # build where
        pass
            
            
    # 增加数据类型为空赋予默认值
    def wrapperFieldDefaultValue(self):
        result = []
        
        allFields = self.mapper.getAllField()
        
        for field in self.getMainFields():
            for mapField in allFields:
                column = str(mapField.get('column', None))
                if column is not None and column == field or (CommonConstants.IGNORE_CASE and column.upper() == field.upper()):
                    if mapField.get('jdbcType').upper() == 'INTEGER':
                        result.append(self.dialect.defaultNnv_template % (self.dialect.isNull, field, self.dialect.nullValue, field))
                    else:
                        result.append(field)
        
        return result
    

class InsertSQLGenerater(SQLGenerater):
    
    insertSql_template = '''insert into %s(%s) 
values (%s)'''


    def __init__(self, mapper):
        '''
        Constructor
        '''
        SQLGenerater.__init__(self, mapper)
        
    def generate(self):
        fields = self.list2Str(self.getMainFields())
        values = self.list2Str(self.generateProValue())
        return self.insertSql_template % (self.tableName, fields, values)

class UpdateSQLGenerater(SQLGenerater):
    set_template = '%s = %s'
    #TODO 丰富where
    updateSql_template = '''update %s
                            set %s '''
    def __init__(self, mapper):
        SQLGenerater.__init__(self, mapper)
        
    # build field = #{}
    def generateProValue(self):
        return [self.set_template % (field[2:field.index(',')], field) for field in SQLGenerater.generateProValue(self)]
            
        
        
    def generate(self):
        fields = self.generateProValue()
        return self.updateSql_template % (self.tableName, self.list2Str(fields))


class DeleteSQLGenerater(SQLGenerater):
    def __init__(self, mapper):
        SQLGenerater.__init__(self, mapper)
        
    def generate(self):
        raise Exception,  'unsupport exception'
        pass
